// #ifndef MP-WEIXIN ||MP-ALIPAY
// 浏览器和React Native
var Fly = require("flyio/dist/npm/fly")
// Node 入口
// var Fly=require("flyio/src/node")
var fly = new Fly;

// #endif
//微信小程序
// #ifdef MP-WEIXIN 
var Fly = require("flyio/dist/npm/wx")
var fly = new Fly()
// #endif
//支付宝小程序
// #ifdef MP-ALIPAY 
var Fly = require("flyio/dist/npm/ap")
var fly = new Fly()
// #endif
// console.log(fly)
let config = {
	baseURL: "https://nuanhudemo.qushen.net",
	headers: {}
	// timeout: 0,
	// parseJson: true,
};

fly.config = config
//请求拦截
fly.interceptors.request.use((request) => {
	request.headers['Content-Type'] = 'application/x-www-form-urlencoded';

	if (uni.getStorageSync('accessToken')) {
		request.headers['Authorization'] = uni.getStorageSync('accessToken');
	}
	console.log(request);
	return request;
})
//返回拦截
fly.interceptors.response.use((response) => {
	console.log('请求返回拦截', response);
	
	return response;
},async (err) => {
	console.log("请求返回拦截", err);
	let response = err.response;
	if (response.data.statusCode == 401) {
		fly.lock();
		// console.log(FLy);
		let newFLy = new Fly();
		newFLy.config = config;
		try{
			newFLy.config.headers['Authorization'] = uni.getStorageSync('refreshToken');
		}catch(e){
			console.log(e);
		}
		// console.log(newFLy);
		// console.log("newFly",newFly);
		try{
			await newFLy.request(err.request.url, err.request.body, {
				method: err.request.method
			}).then(res => {
				fly.unlock();
				if (res.status === 200) {
						console.log(res.headers);
					if (res.headers['x-access-token']) {
						tools.setToken(res.headers['x-access-token'][0], res.headers['x-refresh-token'][0])
					}
					response = res;
			
				} 
				console.log("更新token",res);
			}).catch((err) => {
				if (err.response.data.statusCode == 401) {
					console.log('重新登录');
					fly.unlock();
				}
			})
		}catch(e){
			console.log(e);
		}
		

	}
	return response;
})
class tools {
	static async grequest(obj) {
		// console.log(url, data, config);
		var result;
		await fly.request(
				obj.url, obj.data, {
					method: obj.method
				}
			)
			.then(res => {
				result = res;
				console.log(res)
			})
			.catch(err => {
				result = err;
				console.log(err)
			});
		return result;
	}
	static async setToken(accessToken, refreshToken) {
		uni.setStorageSync('accessToken', accessToken);
		uni.setStorageSync('refreshToken', refreshToken);
	}
}
export default tools;
